package com.csnf.dao.impl;

import com.csnf.dao.IStudentsDao;
import com.csnf.entity.Students;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentsDaoImpl implements IStudentsDao {

    @Override
    public List<Students> findAll() throws IOException {
        SqlSession sqlSession = getSqlSession();
        List<Students> stuList = sqlSession.selectList("com.csnf.dao.IStudentsDao.findAll");
        sqlSession.close();
        return stuList;
    }

    @Override
    public Students findById(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        Students stu = sqlSession.selectOne("com.csnf.dao.IStudentsDao.findById",id);
        sqlSession.close();
        return stu;
    }

    @Override
    public List<Students> findByName(String name) throws IOException {
        SqlSession sqlSession = getSqlSession();
        List<Students> stuList = sqlSession.selectList("com.csnf.dao.IStudentsDao.findByName",name);
        sqlSession.close();
        return stuList;
    }

    @Override
    public void deleteById(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.delete("com.csnf.dao.IStudentsDao.deleteById",id);
        sqlSession.commit();
        sqlSession.close();
        System.out.println("删除成功");

    }

    @Override
    public void update(Students students) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.update("com.csnf.dao.IStudentsDao.update",students);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void add(Students students) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.insert("com.csnf.dao.IStudentsDao.add",students);
        sqlSession.commit();
        sqlSession.close();
    }

    private static SqlSession getSqlSession() throws IOException {
        String path = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(path);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(resourceAsStream);
        SqlSession sqlSession=sqlSessionFactory.openSession();
        return sqlSession;
    }
}
